#include "pluginmgr.h"
#include <QDir>
#include <QAction>


typedef void (*tInitMenu)(QMenu*,QAction**,QString&);


PluginMgr* PluginMgr::singleton = 0;

PluginMgr::PluginMgr()
{

}

PluginMgr& PluginMgr::getInstance(){
    if(!singleton)
        singleton = new PluginMgr;
    return(*singleton);
}

void PluginMgr::Initialize(MainWindow* mainWindow){
    this->mainWindow = mainWindow;
    this->mBar = mainWindow->menuBar();
    pluginMenu = mBar->addMenu("Plugins");

}

QStringList PluginMgr::getModulesList(){
    QDir dir("./plugin");
    QStringList lst;
    lst << "*.plugin";
    lst = dir.entryList(lst,QDir::Files);
    for(int i=0;i<lst.size();i++){
        lst[i] = dir.absoluteFilePath(lst[i]);
    }
    return(lst);
}

void PluginMgr::LoadAllModules(){
    foreach(QString moduleName,getModulesList()){
        Plugin* module = new Plugin(moduleName,pluginMenu);
        pluginsList << module;
    }
}

ImageDocument* PluginMgr::getCurrentDocument(){
    return(mainWindow->GetCurrentDocument());
}

Plugin::Plugin(QString name,QMenu* menu){
    tInitMenu InitMenu;
    moduleHandle = LoadLibrary(name.toStdWString().c_str());
    InitMenu = (tInitMenu)GetProcAddress(moduleHandle,"InitMenu");
    InitPointers = (tInitPointers)GetProcAddress(moduleHandle,"InitPointers");
    QAction* action;
    QString str;
    InitMenu(menu,&action,str);
    pluginFunctions[action] = GetProcAddress(moduleHandle,str.toStdString().c_str());
    connect(action,SIGNAL(triggered (bool)),this,SLOT(PrepareAction()));
}

void Plugin::PrepareAction(){
    InitPointers(PluginMgr::getInstance().getCurrentDocument());
    FARPROC func = pluginFunctions[(QAction*)sender()];
    func();
}

HMODULE Plugin::getHandle() const{
    return(moduleHandle);
}






